<template>
  <div class="upload-container">
    <van-nav-bar
      title="上传电子书"
      style="margin-bottom: 20px;"
    />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="formData.username"
          name="username"
          label="管理员账号"
          placeholder="请输入管理员账号"
          :rules="[{ required: true, message: '请输入管理员账号' }]"
        />
        <van-field
          v-model="formData.password"
          type="password"
          name="password"
          label="管理员密码"
          placeholder="请输入管理员密码"
          :rules="[{ required: true, message: '请输入管理员密码' }]"
        />
        <van-field
          v-model="formData.title"
          name="title"
          label="书名"
          placeholder="请输入书名"
          :rules="[{ required: true, message: '请输入书名' }]"
        />
        <van-field
          v-model="formData.author"
          name="author"
          label="作者"
          placeholder="请输入作者"
          :rules="[{ required: true, message: '请输入作者' }]"
        />
        <!-- <van-field
          v-model="formData.publisher"
          name="publisher"
          label="出版社"
          placeholder="请输入出版社"
        />
        <van-field
          v-model="formData.publishDate"
          name="publishDate"
          label="出版日期"
          placeholder="请输入出版日期"
        /> -->
        <van-field
          v-model="formData.description"
          name="description"
          label="简介"
          type="textarea"
          placeholder="请输入书籍简介"
          :rules="[{ required: true, message: '请输入书籍简介' }]"
        />
        <van-field
          name="type"
          label="书籍类型"
          v-model="selectedTypeName"
          readonly
          placeholder="请选择书籍类型"
          @click="showTypePopup = true"
          :rules="[{ required: true, message: '请选择书籍类型' }]"
        />
        <van-field name="isRecommended" label="是否推荐">
          <template #input>
            <van-switch v-model="formData.isRecommended" size="20" />
          </template>
        </van-field>
      </van-cell-group>

      <div class="upload-files">
        <van-uploader
          v-model="epubFile"
          :max-count="1"
          :before-read="beforeEpubRead"
          @delete="onEpubDelete"
          accept=".epub"
        >
          <van-button icon="plus" type="primary" block>上传电子书文件 (epub)</van-button>
        </van-uploader>

        <van-uploader
          v-model="coverFile"
          :max-count="1"
          :before-read="beforeCoverRead"
          @delete="onCoverDelete"
        >
          <van-button icon="plus" type="primary" block>上传封面图片</van-button>
        </van-uploader>
      </div>

      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>

    <van-popup :show="showDatePicker" position="bottom">
      <van-date-picker
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>

    <van-popup :show="showTypePopup" position="bottom">
      <van-picker
        :columns="bookTypes"
        @confirm="onTypeConfirm"
        @cancel="showTypePopup = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showLoadingToast } from 'vant';
import axios from 'axios';

const router = useRouter();

// 表单数据
const formData = ref({
  username: '18838978186',
  password: '18838978186@zbw',
  title: '', // 书名
  author: '', // 作者
  publisher: '', // 出版社
  publishDate: '', // 出版日期
  description: '', // 简介
  typeId: 1,
  isRecommended: false
});

// 文件上传相关
const epubFile = ref([]);
const coverFile = ref([]);

// 类型选择相关
const showTypePopup = ref(false);
const bookTypes = ref([]);
const selectedTypeName = ref("")
// const selectedTypeName = computed(() => {
//   const selectedType = bookTypes.value.find(type => type.value === formData.value.typeId);
//   return selectedType ? selectedType.text : '';
// });

// 获取书籍类型列表
const fetchBookTypes = async () => {
  try {
    const response = await axios.get('/api/books/types');
    bookTypes.value = response.data.data.map(type => ({
      text: type.type_name,
      value: type.id
    }));
  } catch (error) {
    showToast('获取书籍类型失败');
  }
};

// 文件上传前的验证
const beforeEpubRead = (file) => {
  console.log(file);

  if (file.type !== 'application/epub' && file.type !== 'application/epub+zip') {
    showToast('请上传epub格式的电子书文件');
    return false;
  }
  return true;
};

const beforeCoverRead = (file) => {
  if (!file.type.startsWith('image/')) {
    showToast('请上传图片文件');
    return false;
  }
  return true;
};

// 文件删除处理
const onEpubDelete = () => epubFile.value = [];
const onCoverDelete = () => coverFile.value = [];

// 类型选择处理
const onTypeConfirm = ({ selectedValues, selectedOptions }) => {
  console.log(selectedValues, selectedOptions);
  formData.value.typeId = selectedValues[0];
  selectedTypeName.value = selectedOptions[0].text
  showTypePopup.value = false;
};

// 表单提交处理
const onSubmit = async () => {
  if (!epubFile.value.length) {
    showToast('请上传电子书文件');
    return;
  }

  const loading = showLoadingToast({
    message: '正在上传...',
    forbidClick: true,
    duration: 0
  });

  try {
    formData.value.isRecommended = formData.value.isRecommended ? 1 : 0;
    const formDataToSend = new FormData();
    Object.entries(formData.value).forEach(([key, value]) => {
      formDataToSend.append(key, value);
    });

    formDataToSend.append('epub', epubFile.value[0].file);
    if (coverFile.value.length) {
      formDataToSend.append('cover', coverFile.value[0].file);
    }

    const response = await axios.post('/api/books', formDataToSend);
    loading.close();
    showToast('上传成功');
    // router.push(`/book/${response.data.data.id}`);
  } catch (error) {
    loading.close();
    showToast('上传失败：' + (error.response?.data?.message || error.message));
  }
};

// 初始化获取书籍类型
fetchBookTypes();
</script>

<style lang="scss" scoped>
.upload-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

.upload-files {
  margin: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>